from fastapi import APIRouter, HTTPException
from typing import Dict, Any, List
from pydantic import BaseModel
import os
from loguru import logger

from config import config

router = APIRouter(prefix="/api/v1/config", tags=["配置管理"])

class ASRServiceConfig(BaseModel):
    """ASR服务配置模型"""
    primary_service: str
    fallback_service: str
    enable_speaker_diarization: bool
    default_language: str

class ServiceInfo(BaseModel):
    """服务信息模型"""
    name: str
    description: str
    cost: str
    accuracy: str
    rate_limit: str
    max_audio_length: int
    supported_languages: List[str]
    enabled: bool

class ASRServicesResponse(BaseModel):
    """ASR服务响应模型"""
    success: bool
    services: Dict[str, ServiceInfo]
    primary_service: str
    fallback_service: str

@router.get("/asr/services", response_model=ASRServicesResponse)
async def get_asr_services():
    """获取所有ASR服务信息"""
    """获取所有可用的ASR服务信息，包括成本、准确率、限制等"""
    try:
        services = {}
        for service_name, service_config in config.ASR_SERVICES.items():
            services[service_name] = ServiceInfo(
                name=service_config["name"],
                description=service_config["description"],
                cost=service_config["cost"],
                accuracy=service_config["accuracy"],
                rate_limit=service_config["rate_limit"],
                max_audio_length=service_config["max_audio_length"],
                supported_languages=service_config["supported_languages"],
                enabled=service_config["enabled"]
            )
        
        return {
            "success": True,
            "services": services,
            "primary_service": config.get_primary_asr_service(),
            "fallback_service": config.get_fallback_asr_service()
        }
    except Exception as e:
        logger.error(f"获取ASR服务信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取ASR服务信息失败: {str(e)}")

@router.get("/asr/current", response_model=Dict[str, Any])
async def get_current_asr_config():
    """获取当前ASR配置"""
    """获取当前使用的ASR服务配置"""
    try:
        return {
            "success": True,
            "config": {
                "primary_service": config.get_primary_asr_service(),
                "fallback_service": config.get_fallback_asr_service(),
                "enable_speaker_diarization": config.ASR_CONFIG["enable_speaker_diarization"],
                "default_language": config.ASR_CONFIG["default_language"],
                "audio_preprocessing": config.ASR_CONFIG["audio_preprocessing"]
            },
            "enabled_services": list(config.get_enabled_asr_services().keys())
        }
    except Exception as e:
        logger.error(f"获取当前ASR配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取当前ASR配置失败: {str(e)}")

@router.get("/languages", response_model=Dict[str, Any])
async def get_supported_languages():
    """获取支持的语言列表"""
    """获取所有ASR服务支持的语言列表"""
    try:
        languages = {}
        for service_name, service_config in config.ASR_SERVICES.items():
            if service_config["enabled"]:
                languages[service_name] = {
                    "languages": service_config["supported_languages"],
                    "language_names": {
                        lang: config.get_language_name(lang) 
                        for lang in service_config["supported_languages"]
                    }
                }
        
        return {
            "success": True,
            "languages": languages,
            "language_mapping": config.LANGUAGE_MAPPING,
            "language_names": config.LANGUAGE_NAMES
        }
    except Exception as e:
        logger.error(f"获取支持的语言列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取支持的语言列表失败: {str(e)}")

@router.get("/cost-analysis", response_model=Dict[str, Any])
async def get_cost_analysis():
    """获取成本分析"""
    """分析不同ASR服务的成本对比"""
    try:
        cost_analysis = {}
        for service_name, service_config in config.ASR_SERVICES.items():
            cost_analysis[service_name] = {
                "name": service_config["name"],
                "cost": service_config["cost"],
                "accuracy": service_config["accuracy"],
                "rate_limit": service_config["rate_limit"],
                "max_audio_length": service_config["max_audio_length"],
                "enabled": service_config["enabled"],
                "recommendation": "推荐" if service_name == "google" else "可选"
            }
        
        return {
            "success": True,
            "cost_analysis": cost_analysis,
            "recommendation": {
                "budget_friendly": "google",
                "high_accuracy": "whisper",
                "enterprise": "azure"
            }
        }
    except Exception as e:
        logger.error(f"获取成本分析失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取成本分析失败: {str(e)}")

@router.get("/environment", response_model=Dict[str, Any])
async def get_environment_info():
    """获取环境信息"""
    """获取当前环境配置信息"""
    try:
        env_info = {
            "app_name": config.APP_NAME,
            "app_version": config.APP_VERSION,
            "debug": config.DEBUG,
            "database_url": config.DATABASE_URL,
            "upload_dir": config.UPLOAD_DIR,
            "audio_dir": config.AUDIO_DIR,
            "max_file_size": config.MAX_FILE_SIZE,
            "log_level": config.LOGGING["level"]
        }
        
        # 检查API密钥配置
        api_keys = {
            "openai_api_key": bool(os.getenv("OPENAI_API_KEY")),
            "azure_speech_key": bool(os.getenv("AZURE_SPEECH_KEY")),
            "baidu_app_id": bool(os.getenv("BAIDU_APP_ID")),
            "aliyun_access_key_id": bool(os.getenv("ALIYUN_ACCESS_KEY_ID")),
            "pyannote_token": bool(os.getenv("PYANNOTE_TOKEN"))
        }
        
        return {
            "success": True,
            "environment": env_info,
            "api_keys_configured": api_keys
        }
    except Exception as e:
        logger.error(f"获取环境信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取环境信息失败: {str(e)}")

@router.get("/health", response_model=Dict[str, Any])
async def get_config_health():
    """获取配置健康状态"""
    """检查配置是否正确，服务是否可用"""
    try:
        health_status = {
            "config_valid": True,
            "services_available": [],
            "services_unavailable": [],
            "recommendations": []
        }
        
        # 检查各服务状态
        for service_name, service_config in config.ASR_SERVICES.items():
            if service_config["enabled"]:
                health_status["services_available"].append({
                    "name": service_name,
                    "display_name": service_config["name"],
                    "status": "available"
                })
            else:
                health_status["services_unavailable"].append({
                    "name": service_name,
                    "display_name": service_config["name"],
                    "status": "unavailable",
                    "reason": "未配置API密钥或服务未启用"
                })
        
        # 生成建议
        if not health_status["services_available"]:
            health_status["recommendations"].append("建议至少配置一个ASR服务")
        
        if "google" not in [s["name"] for s in health_status["services_available"]]:
            health_status["recommendations"].append("建议启用Google Speech Recognition作为免费备选方案")
        
        return {
            "success": True,
            "health": health_status
        }
    except Exception as e:
        logger.error(f"获取配置健康状态失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取配置健康状态失败: {str(e)}") 